package com.laikan.reader.bookstart.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import com.baidu.api.Baidu;
import com.baidu.api.BaiduDialog;
import com.baidu.api.BaiduDialogError;
import com.baidu.api.BaiduException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.LoginRequester;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.QQUserInfoBean;
import com.laikan.reader.core.bean.WBUserInfoBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.db.DAO;
import com.mob.tools.utils.UIHandler;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import static com.laikan.library.managers.ToastMgr.showShortToast;

/**
 * 其他登录方式页面
 * 2016-8-10
 */
@SuppressLint ("HandlerLeak")
public class OtherLoginActivity extends BasicActivity implements View.OnClickListener, Handler.Callback {

    private ImageView qq_Login, xinlang_Login, baidu_Login;
    private View zhezhao;
    private LoadingDialog mLoadingDialog;
    private String thirdtype = "1";
    private static final int MSG_USERID_FOUND = 1;
    private static final int MSG_AUTH_CANCEL = 3;
    private static final int MSG_AUTH_ERROR = 4;
    private static final int MSG_AUTH_COMPLETE = 5;
    private TelephonyManager tm;
    private DAO dao;
    // 书架缓存列表
    private ArrayList<Book> cacheBookList;
    private Baidu baidu = null;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bg_view:
                finish();
                break;
            case R.id.login_qq:  // QQ登录
                MobclickAgent.onEvent(mContext, "qq_login");
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    thirdtype = "4";
                    Platform qqPlatform = ShareSDK.getPlatform(this, QQ.NAME);
                    authorize(qqPlatform);
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;
            case R.id.login_xinlang: // 新浪微博登录
                MobclickAgent.onEvent(mContext, "sina_login");
                if(ActivityUitl.isNetworkAvailable(mContext)){
                    thirdtype = "1";
                    Platform weibo = ShareSDK.getPlatform(this, SinaWeibo.NAME);
                    authorize(weibo);
                }else{
                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                }
                break;
            case R.id.login_baidu:  // 百度登录
                MobclickAgent.onEvent(mContext, "baidu_login");
                thirdtype = "5";
                startBaidu();
                break;
            default:
                break;
        }
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_other_login);
        ShareSDK.initSDK(this);
        zhezhao = findViewById(R.id.bg_view);
        qq_Login = (ImageView)findViewById(R.id.login_qq);
        xinlang_Login = (ImageView)findViewById(R.id.login_xinlang);
        baidu_Login = (ImageView)findViewById(R.id.login_baidu);
    }

    @Override
    protected void initData() {
        openEventBus();
        dao = new DAO(mContext);
        tm = (TelephonyManager)getSystemService(mContext.TELEPHONY_SERVICE);
    }

    @Override
    protected void setListener() {
        zhezhao.setOnClickListener(this);
        qq_Login.setOnClickListener(this);
        xinlang_Login.setOnClickListener(this);
        baidu_Login.setOnClickListener(this);
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()){
            case LaiKanEvent.EVENT_ID_FINISH_LOGIN:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                finish();
                return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void authorize(Platform plat) {
        // 已授权
        plat.removeAccount();
        if (plat.isValid()) {    // 判断指定平台是否已经完成授权
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                parseThirdUserInfo(plat);
                UIHandler.sendEmptyMessage(MSG_USERID_FOUND, OtherLoginActivity.this);
                return;
            }
        }

        // 未授权
        plat.setPlatformActionListener(new ShareSDKPlatformActionListener());
        plat.SSOSetting(false);    // true不使用SSO授权，false使用SSO授权
        plat.showUser(null);    // 要数据，不要功能
        // plat.authorize();	// 要功能，不要数据（用户）
    }

    /**
     * 获取用户信息进行登录
     *
     * @param plat
     */
    private void parseThirdUserInfo(Platform plat) {
        String exportData = plat.getDb().exportData();
        Gson gson = new Gson();
        Type type = null;
        String platName = plat.getName();
        if (platName.equals(QQ.NAME)) {
            // 获取QQ用户信息
            QQUserInfoBean userInfo = new QQUserInfoBean();
            type = new TypeToken<QQUserInfoBean>() {
            }.getType();
            userInfo = gson.fromJson(exportData, type);
            SPUtil.putString("openid", userInfo.getUserID());
            SPUtil.putString("dsf_name", userInfo.getNickname());
            LoginRequester.qqLogin(tm, userInfo, dao);

        }else if (platName.equals(SinaWeibo.NAME)) {
            // 获取新浪微博用户信息
            WBUserInfoBean userInfo = new WBUserInfoBean();
            type = new TypeToken<WBUserInfoBean>() {
            }.getType();
            userInfo = gson.fromJson(exportData, type);
            SPUtil.putString("openid", userInfo.getUserID());
            SPUtil.putString("dsf_name", userInfo.getNickname());
            LoginRequester.weiboLogin(tm, userInfo, dao);
        }

        KLog.e("970 plat.getDb().exportData() = " + exportData);
    }

    private class ShareSDKPlatformActionListener implements PlatformActionListener {

        /**
         * 获取授权成功回调
         */
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
            if (action == Platform.ACTION_USER_INFOR) {    // 获取用户信息
                parseThirdUserInfo(platform);
                UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, OtherLoginActivity.this);
            }
        }

        /**
         * 登录失败
         */
        @Override
        public void onError(Platform platform, int action, Throwable t) {
            if (action == Platform.ACTION_USER_INFOR) {
                Message msg = new Message();
                msg.what = MSG_AUTH_ERROR;
                msg.obj = platform.getName();
                UIHandler.sendMessage(msg, OtherLoginActivity.this);
            }
            t.printStackTrace();
        }

        /**
         * 取消登录
         */
        @Override
        public void onCancel(Platform platform, int action) {
            if (action == Platform.ACTION_USER_INFOR) {
                UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, OtherLoginActivity.this);
            }
        }
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_AUTH_CANCEL: {    // 取消登录
                Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_ERROR: {    // 登录失败
                Toast.makeText(this, R.string.auth_error, Toast.LENGTH_SHORT).show();
                // 平台名称
                String platName = (String)msg.obj;
                Platform plat = null;
                if (platName.equals(QQ.NAME)) {
                    // QQ
                    plat = ShareSDK.getPlatform(this, QQ.NAME);
                }else if (platName.equals(SinaWeibo.NAME)) {
                    // 新浪微博
                    plat = ShareSDK.getPlatform(this, SinaWeibo.NAME);
                }
                if (plat != null) {
                    // 删除授权
                    plat.removeAccount(true);
                }
            }
            break;
            case MSG_AUTH_COMPLETE: {    // 授权成功的回调
                // 授权成功，正在跳转登录操作…
                Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    /**
     * 启动 百度登录
     */
    protected void startBaidu() {
        baidu = new Baidu(Constants.APIKEY, OtherLoginActivity.this);
        if (baidu.isSessionValid()) { //避免在Session期内，自动登录
            baidu.clearAccessToken();
            baidu = null;
        }
        baidu = new Baidu(Constants.APIKEY, this);
        baidu.authorize(OtherLoginActivity.this, false, true, new BaiduDialog.BaiduDialogListener() {
            @Override
            public void onComplete(Bundle bundle) {
                LoginRequester.baiduLogin(tm, baidu, dao);
            }

            @Override
            public void onBaiduException(BaiduException e) {
                showShortToast(R.string.login_baidu_failed);
            }

            @Override
            public void onError(BaiduDialogError baiduDialogError) {
                showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onCancel() {
                showShortToast(R.string.login_cancel);
            }
        });
    }

    @Override
    public void onBackPressed() {
        overridePendingTransition(0, R.anim.close);
        super.onBackPressed();
    }
}
